import { ShElement } from './ShElement'


export class ShInput extends ShElement {

    protected $input: HTMLInputElement

    constructor() {
        super()
        
        this.$shadow.innerHTML = `
            <style>
                input {
                    border: var(--border-ctrl);
                    outline: none;
                    width: 100%;
                    padding: 0.5em;
                    font-size: 12px;
                    line-height: calc(1em + 2px);
                    background-color: white;
                }
                input:not([disabled]):hover {
                    border: solid 1px var(--color-primary);
                }
                input[disabled] {
                    background-color: var(--color-ctrl);
                }
                input::placeholder {
                    color: var(--color-text-gray);
                }
            </style>
            <input type="text"></input>
        `

        this.$input = this.$shadow.querySelector('input')!
        this.$input.on('focus', () => this.$input.addClass('sh-focused'))
        this.$input.on('blur', () => this.$input.removeClass('sh-focused'))
    }

    static observedAttributes = ['class', 'style', 'value', 'placeholder', 'readonly', 'disabled']

    attributeChangedCallback(name: string, _: any, newValue: string | null) {

        if (name === 'class')
            this.$input.setClass(newValue || '')
        else if (name === 'style')
            this.$input.style.cssText = newValue || ''
        else if (name === 'value')
            this.$input.value = newValue || ''
        else if (name === 'placeholder')
            this.$input.placeholder = newValue || ''
        else if (name === 'readonly')
            this.$input.readOnly = !(newValue === 'true')
        else if (name === 'disabled')
            this.$input.disabled = !(newValue === 'true')
    }

    public get value(): string {
        return this.$input.value
    }

    public set value(newValue: string) {
        this.$input.value = newValue
    }

    public focus() {
        this.$input.focus()
    }

    public blur() {
        this.$input.blur()
    }

    public clear() {
        this.$input.value = ''
    }
}
customElements.define('sh-input', ShInput)